import moment from 'moment'
export const fileTypeParams: { [key: string]: string } = {
  wordType: `(.doc OR .docx)`,
  excelType: `(.xls OR .xlsx)`,
  pptType: `(.ppt OR .pptx OR .pps OR .ppsx OR .pptm)`,
  pdfType: `(.pdf OR .ofd)`,
  imgType: `(.bmp OR .dib OR .jpeg OR .jpg OR .jpe OR .jp2 OR .png OR .webp OR .pbm OR .pgm OR .ppm OR .pxm OR .pnm OR .pfm OR .sr OR .ras OR .tiff OR .tif OR .exr OR .hdr OR .pic OR .gif)`,
  videoType: `(.mpeg OR .avi OR .3gp OR .rm OR .wmv OR .flv OR .f4v OR .bd OR .mkv)`,
  audioType: `(.wma OR .flac OR .MP3 OR .wav OR .cd OR .RealAudio OR .MP3 OR .MP3pro OR .Ogg OR .ape)`,
  otherType: `!(.doc OR .docx OR 
    .xls OR .xlsx  OR 
    .ppt  OR .pptx  OR .pps  OR .ppsx  OR
    .pptm  OR .pdf  OR .ofd  OR .bmp  OR .dib  OR .jpeg  OR .jpg  OR .jpe  OR .jp2  OR .png  OR 
    .webp  OR .pbm  OR .pgm  OR .ppm  OR .pxm  OR .pnm  OR .pfm  OR .sr  OR .ras  OR .tiff  OR .tif  OR .exr  OR 
    .hdr  OR .pic  OR .gif  OR .mpeg  OR .avi  OR .3gp  OR .rm  OR .wmv  OR .flv  OR .f4v  OR .bd  OR .mkv  OR
    .wma  OR .flac  OR .MP3  OR .wav  OR .cd  OR .RealAudio  OR .MP3  OR .MP3pro  OR .Ogg  OR .ape
    )`
}

// dms转换value的详情值
export const getSearchValue = (value: unknown): any => {
  if (value && Array.isArray(value) && value.length === 0) {
    return '';
  }
  if (value && typeof value === 'object') {
    if (Array.isArray(value) && value.length) {
      return value.map(getSearchValue);
    }
    if (value instanceof Date || value?.['toISOString']) {
      return moment(value).format('YYYY-MM-DD')
    }
    // 成员数据
    // if ('identityid' in value && 'usercode' in value) {
    if ('identityid' in value) {
      //@ts-ignore
      return value.identityid;
    }
    // if ('folderid' in value && 'folderpath' in value && 'foldername' in value) {
    //   //@ts-ignore
    //   return value.folderid;
    // }
    if ('folderid' in value) {
      //@ts-ignore
      return value.folderid;
    }
    //@ts-ignore
    if (value.text && value.value) {
      //@ts-ignore
      return value.value;
    }
    return JSON.stringify(value);
  } else {
    return (value as string)?.toString?.();
  }
};

export const getDMSValue = ({ key, value, type }: { key: string; value: unknown; type: string }) => {
  const newValue = getSearchValue(value);
  if (newValue) {
    if (Array.isArray(newValue)) {
      if (key?.toLowerCase() === 'filesize') {
        if (newValue.length && (newValue[0] !== undefined || newValue[1] !== undefined)) {
          return `${key.toLowerCase()}:[${newValue
            .map((item) => Number(item) * 1024 * 1024)
            .join(' TO ')}]`;
        } else {
          return '';
        }
      }
      // 暂时注释, 还不知道masterfilepath的用处
      // else if (key.toLowerCase() === 'filepath') {
      //   return `(filepath:(*${newValue[0]}*) OR masterfilepath:(*${newValue[0]}*))`
      // }
      return key ? `${key.toLowerCase()}:(${newValue.join(' OR ')})` : '';
    } else {
      if (newValue === '[]') {
        return '';
      }

      if (key.toLowerCase() === 'foldername' && value) {
        return `(${key.toLowerCase()}:(${newValue}) OR suggest:(*${value}*) OR foldername_suggest:(*${value}*))`;
      } else if (key.toLowerCase() === 'filename' && value) {
        return `(${key.toLowerCase()}:(${newValue}) OR suggest:(*${value}*) OR filename_suggest:(*${value}*))`;
      } else if (key.toLowerCase() === 'filetag' && value) {
        return `(filetag:(*${value}*) OR filetag_suggest:(*${value}*))`
      } else if (key.toLowerCase() === 'fileextname' && value) {
        return getfileextnameString(value)
      }
      if (type?.includes('DateTime') || newValue.includes('$$')) {
        if (newValue === '$$') {
          return '';
        }
        return `${key.toLowerCase()}:[${newValue.replace('$$', ' TO ')}]`;
      } else {
        return `${key.toLowerCase()}:(${newValue})`;
      }
    }
  }
  return '';
};

export const getDmsSearchData = (
  list: {
    key: string;
    value: unknown;
    type: string;
  }[],
) => {
  const data = list
    .filter((item) => item.value || item.value === 0)
    .reduce((pre, next) => {
      const value = getDMSValue(next);
      if (value) {
        pre += ' AND ' + value;
      }
      return pre;
    }, '');
  return data.slice(5);
};

export const getPageSearchData = (data: object) => {
  let SearchWhere = '';
  Object.entries(data).forEach(([key, value]) => {
    if (value && Array.isArray(value) && value.length === 0) {
      return;
    }
    if (value || value === 0) {
      if (typeof value === 'object') {
        if (Array.isArray(value) && value.length) {
          if (value[0] instanceof Date || value?.[0]?.toDate) {
            SearchWhere += ` AND ${key}:[${getSearchValue(value).join(' TO ')}]`;
          } else {
            SearchWhere += ` AND ${key}:(${getSearchValue(value).join(' OR ')})`;
          }
        } else if (key?.toLowerCase() === 'filesize') {
          //暂时这么写
          if (value.value.length && (value.value[0] !== undefined || value.value[1] !== undefined)) {
            SearchWhere += ` AND ${key.toLowerCase()}:[${value.value
              .map((item) => Number(item) * 1024 * 1024)
              .join(' TO ')}]`
          } else {
            SearchWhere += ` AND ${key}:(${getSearchValue(value).join(' OR ')})`;
          }
        }
      } else {
        SearchWhere += ` AND ${key}:(${value})`;
      }
    }
  });
  return SearchWhere.slice(5);
};

export const getsourceUserString = (sourceUser, userType) => {
  const value = sourceUser
  return ` AND ${userType}:(${value[0].identityid})`
}

export const getfileextnameString = (fileextname, needAND?) => {
  if (fileextname.includes('AND')) {
    if (needAND) {
      return ` AND !(fileextname:${fileextname.replaceAll('AND', 'OR')})`
    }
    return ` !(fileextname:${fileextname.replaceAll('AND', 'OR')})`
  } else {
    if (needAND) {
      return ` AND fileextname:${fileextname}`
    }
    return ` fileextname:${fileextname}`
  }
}

export const gettimeRangeString = (timeRange, userType) => {
  const value = timeRange
  const value0 = moment(value[0]).format('YYYY-MM-DD')
  const value1 = moment(value[1]).format('YYYY-MM-DD')

  return ` AND ${userType}:[${value0} TO ${value1}]`
}

export interface ConditionItemType {
  key: string;
  type: string;
  label: string;
  controlType: string;
  controlId: string;
  options: { text: string; value: string | number }[];
  mode: 'singleSelectbox' | 'multipleSelectbox' | 'single' | 'multiple' | '';
  value: any;
}

// 文件基本schema
export const fileschemaOptions: ConditionItemType[] = [
  {
    // 内容
    key: 'filecontent',
    type: 'EDoc2.Meta.String',
    label: 'SearchEngine.content',
    controlType: 'edoc2Textbox',
    controlId: 'edoc2Textbox0',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 编号
    key: 'filecode',
    type: 'EDoc2.Meta.String',
    label: 'SearchEngine.number',
    controlType: 'edoc2Textbox',
    controlId: 'edoc2Textbox6',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 密级
    key: 'securitylevelid',
    type: 'EDoc2.Meta.Dropdown',
    label: 'SearchEngine.classification',
    controlType: 'edoc2Selectbox',
    controlId: 'edoc2Selectbox9',
    options: [
      { text: 'SearchEngine.unclassified', value: 1 },
      { text: 'SearchEngine.inside', value: 2 },
      { text: 'SearchEngine.secret', value: 3 },
      { text: 'SearchEngine.confidential', value: 4 },
    ],
    mode: 'singleSelectbox',
    value: '',
  },
  {
    // 版本
    key: 'filenumstr',
    type: 'EDoc2.Meta.String',
    label: 'SearchEngine.edition',
    controlType: 'edoc2Textbox',
    controlId: 'edoc2Textbox10',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 备注
    key: 'fileremark',
    type: 'EDoc2.Meta.String',
    label: 'SearchEngine.remarks',
    controlType: 'edoc2Textbox',
    controlId: 'edoc2Textbox11',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 标签
    key: 'filetag',
    type: 'EDoc2.Meta.String',
    label: 'SearchEngine.label',
    controlType: 'edoc2Textbox',
    controlId: 'edoc2Textbox12',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 文件大小
    key: 'filesize',
    type: 'EDoc2.Meta.String',
    label: 'SearchEngine.fileSize',
    controlType: 'edoc2FileSize',
    controlId: 'edoc2FileSize01',
    options: [],
    mode: '',
    value: [],
  },
];
// 元数据基本schema
export const metaSchema: ConditionItemType[] = [
  {
    // 数字框
    key: '',
    type: 'edoc2Number',
    controlType: 'edoc2Number',
    controlId: '',
    label: '',
    options: [],
    mode: '',
    value: '',
  },
  {
    // textarea
    key: '',
    type: 'edoc2TextArea',
    controlId: '',
    controlType: 'edoc2TextArea',
    label: '',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 富文本
    key: '',
    type: 'edoc2RichText',
    controlId: '',
    controlType: 'edoc2RichText',
    label: '',
    options: [],
    mode: '',
    value: '',
  },
  {
    // 开关
    key: '',
    type: 'edoc2Switch',
    controlId: '',
    controlType: 'edoc2Switch',
    label: '',
    options: [],
    mode: '',
    value: '',
  },
];


export const formatTypes = (obj: {
  FileExtNameCode: string,
  FileExtNameOrder: number,
  FileExtNameTxt: string,
  FileExtNameValue: string,
}) => {
  const typesArray = obj.FileExtNameValue.split(',')
  let newtypes = typesArray.join(' OR ')
  if (obj.FileExtNameCode == 'other') {
    // 用于判断是不是其他类型, 调接口时再换回来
    newtypes = typesArray.join(' AND ')
    return `(${newtypes})`
  }
  return `(${newtypes})`
}